<?php
require_once 'Zend/Controller/Action.php';

class SellController extends App_Zend_Controller_Action_Shop 
{
	public $FACEBOOK_CONSUMER_ID = '';
	public $FACEBOOK_SECRET_ID = '';
	
	public $inv = 0;
	public $itemid = 0;
	
	public function init()
	{
		try{
			$config = new Zend_Config_Xml(MY_ROOT.'/html/upload/game/configs.xml');
			$config = $config->toArray();
		} catch (Exception $e) {
			die('error game configs');
		}
		if(empty($config))
			die('error game configs');
		//初始化配置
		$this->FACEBOOK_CONSUMER_ID = $config['FacebookInfo']['Facebook_Key'];
		$this->FACEBOOK_SECRET_ID = $config['FacebookInfo']['Facebook_Secret'];
	}
	
	public function indexAction()
	{		
		$this->getHelper('layout')->disableLayout();
		
		$inv = $this->getRequest()->getParam('i', 0); //邀请人
		//unset($_SESSION['current_fb_user']);exit();
		$pattern = '/\d+/';		
		if(!empty($inv) && !preg_match($pattern, $inv)) {
			exit();
		}	
		if (empty($inv)) { //没有邀请人
			$renderView = 'index';
		} else {
			$this->inv = $inv;			
			$itemid = $this->getRequest()->getParam('itemid', 0);
			$itemid = intval($itemid);			
			$this->itemid = $itemid;
			$config = new Zend_Config_Xml(MY_ROOT.'/html/upload/game/configs.xml');
			$config = $config->toArray();
			$this->view->img = '';
			foreach ($config['Pictures']['Picture'] as $v) {
				if ($v['Picture_ID'] == $itemid) {					
					$this->view->img = $v['Picture_Url'];										
				}
			}
			$this->view->link = '/sell-redirect?i=' . $inv . '&itemid=' . $itemid;
			$renderView = 'indexshare';
		}
		$this->view->shareLink = MY_URL . "/game-index/?f=" . $inv;
		$currentUserId = $this->_getCurrentUser();	
		$this->view->currentUserId = $currentUserId;
		$memberModel = new CPyramidMember();
		
		$memberModel->add(array('facebook_id'=>$currentUserId, 'inviter_facebook_id'=>empty($inv)?0:$inv, 'add_time'=>time()));
		
		//分享信息
		$shareModel = new CPyramidMemberShare();
		
		$myShareCount = $shareModel->getMyShareCount($currentUserId);
		$friendsShareCount = $shareModel->getFriendsShareCount($currentUserId);
		
		//访问信息
		$visitModel = new CPyramidMemberVisit();
				
		$friendsVisitCount = $visitModel->getFriendsVisitCount($currentUserId);
		$interestedFriendsCount = $friendsVisitCount;
		
		//购买信息
		$buyModel = new CPyramidMemberBuy();		
		$myBuyAmount = $buyModel->getMyBuyAmount($currentUserId);
		$friendsBuyAmount = $buyModel->getFriendBuyAmount($currentUserId);
		$buyFriends = $buyModel->getCountBuyFriend($currentUserId);
		
		//佣金信息
		$accountDetailModel = new CPyramidAccountDetail();
		$profit = $accountDetailModel->getMyAmount($currentUserId);
		
		//现金账户
		$accountModel = new CPyramidMemberAccount();
		$cash = $accountModel->getMyCash($currentUserId);
		$rank = $accountModel->getRank($currentUserId);
	
		$this->view->myShareCount = $myShareCount;
		$this->view->friendsShareCount = $friendsShareCount;
		
		$this->view->friendsVisitCount = $friendsVisitCount;
		$this->view->interestedFriendsCount = $interestedFriendsCount;
		
		$this->view->myBuyAmount = $myBuyAmount;
		$this->view->friendsBuyAmount = $friendsBuyAmount;
		$this->view->buyFriends = $buyFriends;
		$this->view->profit = $profit;
		$this->view->rank = $rank;
		
		$this->view->cash = $cash;
		
		$this->render($renderView);
	}
	
	public function redirectAction()
	{
		$this->getHelper('layout')->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
		
		$inv = $this->getRequest()->getParam('i', 0);		
		$itemid = $this->getRequest()->getParam('itemid', 0);
		
		$itemid = intval($itemid);
		
		$pattern = '/\d+/';
		
		if(empty($inv) || !preg_match($pattern, $inv)) {
			exit();
		}		
		
		if (empty($itemid)) {
			exit();
		}
		
		$currentUserId = $this->_getCurrentUser();
		
		setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time()+3600*24*365, '/');
		setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time()+3600*24*365, '/');
		
		$visitModel = new CPyramidMemberVisit();
		$visitModel->add(array('facebook_id'=>$currentUserId, 'from_facebook_id'=>$inv, 'ip'=>$_SERVER['REMOTE_ADDR'], 'itemid'=>$itemid, 'add_time'=>time()));
		
		$this->_redirect('/pd-' . $itemid . '.html');
		//echo '<script>top.location.href="' . MY_URL . '/pd-' . $itemid . '.html";</script>';
	}
	
	public function adAction()
	{
		$this->getHelper('layout')->disableLayout();
		$this->link = '';
	}
	
	public function cashAction()
	{
		$this->getHelper('layout')->disableLayout();
		$currentUserId = $this->_getCurrentUser();
		$email = $this->getRequest()->getParam('email', '');
		$amount = $this->getRequest()->getParam('amount', 0);
		
		$validator = new Zend_Validate_EmailAddress();

		if (!$validator->isValid($email)) {
			exit(0);
		}
		
		if (!preg_match('/^[^0]\d*(\.\d{2})?/', $amount)) {
			exit(1);
		}
		
		$accountModel = new CPyramidMemberAccount();
		$accountMount = $accountModel->getMyCash($currentUserId);
		
		if ($amount > $accountMount) {		
			echo 2;
			exit();
		}
		
		$cashModel = new CPyramidAccountCrash();
		$db = $accountModel->getAdapter();
		$db->beginTransaction();
		try {
			$cashModel->add(array('facebook_id'=>$currentUserId, 'amount'=>$amount, 'email'=>$email, 'add_time'=>time()));
			$accountModel->subAmount($amount, $currentUserId);
			$db->commit();
			echo 5;
			exit();
		} catch (Exception $e) {
			$db->rollBack();
			echo 3;
			exit();
		}
	}
	
	private function _oauth()
	{
    	$canvas_page = "http://apps.facebook.com/sharejersey?";
    	
    	if ($this->inv) {
    		$canvas_page .= 'i=' . $this->inv . '&';
    	}
    	if ($this->itemid) {
    		$canvas_page .= 'itemid=' . $this->itemid . '&';
    	}
    	
	    $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
	            . $this->FACEBOOK_CONSUMER_ID . "&redirect_uri=" . urlencode($canvas_page) . '&scope=publish_stream,user_photos';
	    $signed_request = $_REQUEST["signed_request"];
	    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	    $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
	    if (empty($data["user_id"])) {
	            echo("<script> top.location.href='" . $auth_url . "'</script>");
	            exit();
	    }
	    $_SESSION['current_fb_user'] = $data["user_id"];	     
    }
    
    protected function _getCurrentUser()
    {
    	if (isset($_SESSION['current_fb_user'])) {
			$currentUserId = $_SESSION['current_fb_user'];
		} else {
			$this->_oauth();
			$currentUserId = $_SESSION['current_fb_user'];
		}
		
		return $currentUserId;
    }
    
    public function clearAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		unset($_SESSION['current_fb_user']);
    }
    
	public function dataAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$detailModel = new CPyramidAccountDetail();
		$currentUserId = $this->getRequest()->getParam('u', 0);
		$today = date('Y-m-d', time());
		$firstDay = date('Y-m-d', time() - 3600*24*30);
		
		$dataRow = $detailModel->getMyData($today, $firstDay, $currentUserId);
		
		$dataArray = array();
		
		for ($i = 30; $i>=0; $i--) {
			$dataArray[] = date('m-d', time()-3600*24*$i);
		}
		
		$return = array();
		
		foreach ($dataArray as $v) {
			$return[$v] = '0';			
		}
		foreach ($dataRow as $v) {
			if (!empty($v['add_time'])) {
				$return[date('m-d', $v['add_time'])] += $v['sum_amount'];
			}
		}	
		
		$date = array_keys($return);
		$include = array_values($return);	
		
		include MY_ROOT . '/library/Flash/open-flash-chart.php'; 		 
		 
		$chart = new open_flash_chart(); 
		$chart->set_bg_colour('#FFFFFF');
				
		$titleStr = 'My earn';
		
		
//		$title = new title($titleStr); 
//		$title->set_style( "{font-size: 12px; text-align: center;}" ); 
//		$chart->set_title( $title ); 		
		
		 
		$area = new area(); 
		$area->set_colour( '#5B56B6' ); 
		$area->set_values( $include ); 		
		$area->set_key( 'Money:($)', 8 ); 
		$chart->add_element( $area ); 
		 
		$x_labels = new x_axis_labels(); 
		$x_labels->set_steps( 10 ); 
		$x_labels->set_vertical(); 
		$x_labels->rotate('0'); 
		$x_labels->set_colour( '#000000' ); 
		$x_labels->set_labels( $date ); 
		 
		$x = new x_axis(); 
		$x->set_colour( '#000000' ); 
		$x->set_grid_colour( '#acacac' ); 
		$x->set_offset( false ); 
		$x->set_steps(1); 
		// Add the X Axis Labels to the X Axis 
		$x->set_labels( $x_labels ); 
		 
		$chart->set_x_axis( $x ); 
		 
		// 
		// LOOK: 
		// 
		$x_legend = new x_legend(); 
		$x_legend->set_style( '{font-size: 100px; color: #000000}' ); 
		$chart->set_x_legend( $x_legend ); 
		 
		// 
		// remove this when the Y Axis is smarter 
		// 
		$y = new y_axis(); 
		$y->set_range( 0, max($include)+1, 10 ); 
		$y->set_colour('#000000');
		$y->set_grid_colour('#dddddd'); 
		$y->set_steps( 100 ); 
		$chart->add_y_axis($y); 
		 
		echo $chart->toPrettyString(); 
	}
}